<?php

namespace app\logic;

use app\model\Group as GroupModel;
use app\model\Menu as MenuModel;
use app\model\Sjoin as SjoinModel;
use think\db\Query;

class MenuLogic
{
    /**
     * @var MenuModel
     */
    private MenuModel $menuModel;

    /**
     * @var string
     */
    private string $menuWhere;

    /**
     * @var array;
     */
    private array $addMenu;


    /**
     * @param MenuModel $menuModel
     */
    public function __construct(MenuModel $menuModel)
    {
        $this->menuModel = $menuModel;
    }

    /**
     * @param int $pid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMenuList(int $pid): array
    {
        $this->menuWheres();
        $this->addMenu = $this->menuModel
            ->field('id,num,url,icons,name,pid')
            ->whereRaw("status = 1 {$this->menuWhere}")
            ->order('sort,id')
            ->select()
            ->toArray();

        return $this->getMenu($pid);
    }


    private function menuWheres()
    {
        $this->menuWhere = '';
        $myExt = cache('Admin-Menu-ids:' . request()->ADMIN_INFO['id']);

        if (empty($myExt)) {
            $myExt = '0';
        }

        if ($myExt != '-1') {
            $this->menuWhere = ' and `id` in(' . str_replace(array('[', ']'), array('', ''), $myExt) . ')';
        }

        if (request()->ADMIN_INFO['id'] != 1) {
            //非admin只能看普通菜单
            $this->menuWhere .= ' and `type` = 0';
        }
    }

    /**
     * @param $pid
     * @param int $lx
     * @return array
     */
    private function getMenu($pid, $lx = 0): array
    {
        $menu = $this->addMenu;
        $rows = [];
        foreach ($menu as $rs) {
            if ($lx == 0 && $pid != $rs['pid']) {
                continue;
            }
            $num = $rs['num'];
            $rs['bh'] = $num;
            $sid = $rs['id'];
            $icons = $rs['icons'];
            if (empty($num)) {
                $num = 'num' . $sid;
            }
            if (empty($icons)) {
                $icons = 'bookmark-empty';
            }
            $rs['icons'] = $icons;
            $rs['num'] = $num;
            if ($lx == 0) {
                $children = $this->getmenu($sid);
                $rs['children'] = $children;
                $rs['stotal'] = count($children);
            } else {
                $rs['stotal'] = 0;
            }
            $rows[] = $rs;
        }
        return $rows;
    }
}